package com.easylinkin.linkappapi.lobar.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.lobar.dto.UserGateDTO;
import com.easylinkin.linkappapi.lobar.entity.UserGate;
import com.easylinkin.linkappapi.lobar.service.UserGateService;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: 项目闸机管理
 */
@RestController
@RequestMapping("userGate")
@Api(tags = "项目闸机管理")
public class UserGateController {
  
  @Autowired
  private UserGateService userGateService;

  /**
   * @Description: 增加闸机
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping
  @ApiOperation("增加闸机")
  public RestMessage insert(@RequestBody UserGate userGate){
    //todo 参数验证
    userGateService.insert(userGate);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 删除闸机（包含批量删除）
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @DeleteMapping
  @ApiOperation("删除闸机（包含批量删除）")
  public RestMessage delBatch(@RequestBody UserGate userGate){
    Assert.notEmpty(userGate.getIds(),"id不能为空");
    userGateService.removeByIds(userGate.getIds());
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 编辑闸机
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PutMapping
  @ApiOperation("编辑闸机")
  public RestMessage updateById(@RequestBody UserGate userGate){
    Assert.notNull(userGate.getId(),"id不能为空");
    userGateService.updateOne(userGate);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 根据id查询闸机详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("{id}")
  @ApiOperation("根据id查询闸机详情")
  public RestMessage findById(@PathVariable("id")String id) {
    Assert.notNull(id,"id不能为空");
    UserGate userGate = userGateService.getById(id);
    return RestBuilders.successBuilder().data(userGate).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryListByPage(@RequestBody RequestModel<UserGateDTO> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<UserGateDTO> record =  userGateService.queryListByPage(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询月视图
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("month/list")
  @ApiOperation("根据条件，分页(不分页)查询月视图")
  public RestMessage queryMonthByPage(@RequestBody RequestModel<UserGateDTO> requestModel)
      throws ExecutionException, InterruptedException {
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<UserGateDTO> record =  userGateService.queryMonthByPage(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，导出
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("month/export")
  @ApiOperation("根据条件，导出")
  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "导出健康管理月视图")
  public void monthExport(@RequestBody RequestModel<UserGateDTO> requestModel, HttpServletRequest request, HttpServletResponse response)
      throws ExecutionException, InterruptedException {
    requestModel.getPage().setSize(-1);
    IPage<UserGateDTO> iPage = userGateService.queryMonthByPage(requestModel);
    List<Map<String, Object>> maps = new ArrayList<>();
    if (null != iPage.getRecords() && iPage.getRecords().size()>0){
      for (int i = 0; i < iPage.getRecords().size(); i++) {
        UserGateDTO userGateDTO = iPage.getRecords().get(i);
        Map<String, Object> map = new HashMap<>();
        map.put("id",i+1);
        map.put("userName",userGateDTO.getUserName());
        userGateDTO.getMouthList().forEach(m ->{
          map.put(m.getId(),m.getOnFlagStr());
        });
        map.put("count",userGateDTO.getOnNum());
        maps.add(map);
      }
    }
    //计算总天数
    String[] split = requestModel.getCustomQueryParams().getMouthStr().split("-");
    int lengthOfMonth = DateUtil
        .lengthOfMonth(Integer.valueOf(split[1]), DateUtil.isLeapYear(Integer.valueOf(split[0])));
    String keyValue = "序号:id,姓名:userName";
    for (int i = 1; i <= lengthOfMonth; i++) {
      keyValue += ","+i+":"+i;
    }
    keyValue += ",合计:count";
    String title = requestModel.getCustomQueryParams().getMouthStr()+"健康管理";
    String fileName = title + ".xls";
    try {
      OutputStream outputStream = OutputStreamUtil
          .getOutputStream(request, response, fileName);
      ExcelTools.exportExcel(outputStream, keyValue, maps, ExcelConstant.XLS, title);
      response.flushBuffer();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
    } catch (Exception e) {
      throw new RuntimeException("excel导出失败！" + e.getMessage());
    }
  }

  /**
   * @Description: 根据条件，导出
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("export")
  @ApiOperation("根据条件，导出")
  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "导出健康管理报表")
  public void export(@RequestBody RequestModel<UserGateDTO> requestModel, HttpServletRequest request, HttpServletResponse response) {
    requestModel.getPage().setSize(-1);
    IPage<UserGateDTO> iPage = userGateService.queryListByPage(requestModel);
    iPage.getRecords().forEach(r ->{
      //数据转换
      if (null != r.getTime()){
        r.setTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(r.getTime()));
      }
      r.setTemperatureStr(r.getTemperature()+"°c");
      String[] code = {"","绿码","黄码","灰码","红码"};
      r.setHealthCodeStr(code[r.getHealthCode()]);
//      r.setTravelCodeStr(Integer.valueOf(1).equals(r.getTravelCode())?"正常":"异常");
      r.setTravelCodeStr("-");
    });
    String keyValue = "姓名:userName,班组:groupName,参建单位:companyName,"
        + "工种:workType,体温:temperatureStr,健康码:healthCodeStr,行程码:travelCodeStr,测量时间:timeStr";
    String title = "健康管理";
    String fileName = title + ".xls";
    try {
      OutputStream outputStream = OutputStreamUtil
          .getOutputStream(request, response, fileName);
      ExcelTools.exportExcel(outputStream, keyValue, iPage.getRecords(), ExcelConstant.XLS, title);
      response.flushBuffer();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
    } catch (Exception e) {
      throw new RuntimeException("excel导出失败！" + e.getMessage());
    }
  }

  /**
   * @Description: 根据月份获取当月天数
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("mouthDay/{mouthStr}")
  @ApiOperation("根据id查询闸机详情")
  public RestMessage mouthDay(@PathVariable("mouthStr")String mouthStr) {
    //计算总天数
    String[] split = mouthStr.split("-");
    int lengthOfMonth = DateUtil
        .lengthOfMonth(Integer.valueOf(split[1]), DateUtil.isLeapYear(Integer.valueOf(split[0])));
    return RestBuilders.successBuilder().data(lengthOfMonth).build();
  }
}

